import React, { useState, useEffect } from 'react';
import { Table, Button, Modal, Form, Input, Select, message, Divider, Space } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, SearchOutlined, BookOutlined, PlusCircleOutlined, MinusCircleOutlined } from '@ant-design/icons';
import { getDictionaries, createDictionary, updateDictionary, deleteDictionary } from '../../services/api';

const { Option } = Select;

const DictionaryConfig = () => {
  const [dictionaries, setDictionaries] = useState([]);
  const [loading, setLoading] = useState(false);
  const [visible, setVisible] = useState(false);
  const [itemVisible, setItemVisible] = useState(false);
  const [editMode, setEditMode] = useState(false);
  const [itemEditMode, setItemEditMode] = useState(false);
  const [currentDict, setCurrentDict] = useState({});
  const [currentItem, setCurrentItem] = useState({});
  const [form] = Form.useForm();
  const [itemForm] = Form.useForm();
  const [searchText, setSearchText] = useState('');

  useEffect(() => {
    fetchDictionaries();
  }, []);

  const fetchDictionaries = async () => {
    setLoading(true);
    try {
      const data = await getDictionaries();
      setDictionaries(data);
    } catch (error) {
      message.error('获取字典列表失败');
      console.error('Failed to fetch dictionaries:', error);
    }
    setLoading(false);
  };

  const handleAdd = () => {
    setEditMode(false);
    setCurrentDict({ items: [] });
    form.resetFields();
    setVisible(true);
  };

  const handleEdit = (dict) => {
    setEditMode(true);
    setCurrentDict(dict);
    form.setFieldsValue(dict);
    setVisible(true);
  };

  const handleDelete = async (id) => {
    try {
      await deleteDictionary(id);
      message.success('删除字典成功');
      fetchDictionaries();
    } catch (error) {
      message.error('删除字典失败');
      console.error('Failed to delete dictionary:', error);
    }
  };

  const handleSubmit = async (values) => {
    try {
      if (editMode) {
        await updateDictionary(currentDict.id, values);
        message.success('更新字典成功');
      } else {
        await createDictionary(values);
        message.success('创建字典成功');
      }
      setVisible(false);
      fetchDictionaries();
    } catch (error) {
      message.error(editMode ? '更新字典失败' : '创建字典失败');
      console.error('Failed to submit dictionary:', error);
    }
  };

  const handleAddItem = (dict) => {
    setCurrentDict(dict);
    setItemEditMode(false);
    setCurrentItem({});
    itemForm.resetFields();
    setItemVisible(true);
  };

  const handleEditItem = (dict, item) => {
    setCurrentDict(dict);
    setItemEditMode(true);
    setCurrentItem(item);
    itemForm.setFieldsValue(item);
    setItemVisible(true);
  };

  const handleDeleteItem = (dict, itemId) => {
    const updatedItems = dict.items.filter(item => item.id !== itemId);
    const updatedDict = { ...dict, items: updatedItems };
    setCurrentDict(updatedDict);
    // 更新表单中的items字段
    form.setFieldsValue({ items: updatedItems });
  };

  const handleItemSubmit = async (values) => {
    try {
      let updatedItems = [...currentDict.items];

      if (itemEditMode) {
        // 更新现有项
        updatedItems = updatedItems.map(item =>
          item.id === currentItem.id ? { ...item, ...values } : item
        );
      } else {
        // 添加新项
        const newItem = {
          id: updatedItems.length > 0 ? Math.max(...updatedItems.map(item => item.id)) + 1 : 1,
          ...values
        };
        updatedItems.push(newItem);
      }

      // 更新字典
      const updatedDict = { ...currentDict, items: updatedItems };
      await updateDictionary(updatedDict.id, updatedDict);
      message.success('更新字典项成功');
      setItemVisible(false);
      fetchDictionaries();
    } catch (error) {
      message.error('更新字典项失败');
      console.error('Failed to submit dictionary item:', error);
    }
  };

  const filteredDictionaries = dictionaries.filter(dict =>
    dict.name.toLowerCase().includes(searchText.toLowerCase()) ||
    dict.code.toLowerCase().includes(searchText.toLowerCase()) ||
    dict.description.toLowerCase().includes(searchText.toLowerCase())
  );

  // 字典列表列定义
  const columns = [
    { title: 'ID', dataIndex: 'id', key: 'id' },
    { title: '字典名称', dataIndex: 'name', key: 'name' },
    { title: '字典编码', dataIndex: 'code', key: 'code' },
    { title: '描述', dataIndex: 'description', key: 'description' },
    { title: '项数量', dataIndex: 'items', key: 'itemCount', render: items => items.length },
    { title: '状态', dataIndex: 'status', key: 'status', render: status => (
      <span style={{ color: status === 'active' ? 'green' : 'red' }}>
        {status === 'active' ? '启用' : '禁用'}
      </span>
    )},
    { title: '操作', key: 'action', render: (_, record) => (
      <Space>
        <Button
          type="primary"
          icon={<EditOutlined />}
          size="small"
          onClick={() => handleEdit(record)}
        >
          编辑
        </Button>
        <Button
          type="danger"
          icon={<DeleteOutlined />}
          size="small"
          onClick={() => handleDelete(record.id)}
        >
          删除
        </Button>
      </Space>
    )}
  ];

  // 字典项表格列定义
  const itemColumns = [
    { title: 'ID', dataIndex: 'id', key: 'id' },
    { title: '项文本', dataIndex: 'label', key: 'label' },
    { title: '项值', dataIndex: 'value', key: 'value' },
    { title: '排序', dataIndex: 'sort', key: 'sort' },
    { title: '状态', dataIndex: 'status', key: 'status', render: status => (
      <span style={{ color: status === 'active' ? 'green' : 'red' }}>
        {status === 'active' ? '启用' : '禁用'}
      </span>
    )},
    { title: '操作', key: 'action', render: (_, record) => (
      <Space>
        <Button
          type="primary"
          icon={<EditOutlined />}
          size="small"
          onClick={() => handleEditItem(currentDict, record)}
        >
          编辑
        </Button>
        <Button
          type="danger"
          icon={<DeleteOutlined />}
          size="small"
          onClick={() => handleDeleteItem(currentDict, record.id)}
        >
          删除
        </Button>
      </Space>
    )}
  ];

  return (
    <div className="dictionary-config">
      <div className="header">
        <h2>字典配置</h2>
        <div className="search-bar">
          <Input
            placeholder="搜索字典名称、编码或描述"
            prefix={<SearchOutlined />}
            value={searchText}
            onChange={e => setSearchText(e.target.value)}
          />
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
            新增字典
          </Button>
        </div>
      </div>

      <Table
        columns={columns}
        dataSource={filteredDictionaries}
        loading={loading}
        rowKey="id"
        pagination={{ pageSize: 10 }}
      />

      {/* 字典编辑模态框 */}
      <Modal
        title={editMode ? '编辑字典' : '新增字典'}
        visible={visible}
        onOk={form.submit}
        onCancel={() => setVisible(false)}
        width={800}
      >
        <Form form={form} layout="vertical" onFinish={handleSubmit}>
          <Form.Item
            name="name"
            label="字典名称"
            rules={[{ required: true, message: '请输入字典名称' }]}
          >
            <Input placeholder="请输入字典名称" />
          </Form.Item>

          <Form.Item
            name="code"
            label="字典编码"
            rules={[{ required: true, message: '请输入字典编码' }]}
          >
            <Input placeholder="请输入字典编码" />
          </Form.Item>

          <Form.Item name="description" label="描述">
            <Input.TextArea placeholder="请输入字典描述" />
          </Form.Item>

          <Form.Item name="status" label="状态" rules={[{ required: true, message: '请选择状态' }]}>
            <Select placeholder="请选择状态">
              <Option value="active">启用</Option>
              <Option value="inactive">禁用</Option>
            </Select>
          </Form.Item>

          <Divider>
            <BookOutlined /> 字典项
          </Divider>

          <div className="dictionary-items">
            <Button
              type="dashed"
              icon={<PlusCircleOutlined />}
              onClick={() => handleAddItem(currentDict || { items: [] })}
              style={{ marginBottom: 16 }}
            >
              新增字典项
            </Button>

            <Table
              columns={itemColumns}
              dataSource={currentDict.items || []}
              rowKey="id"
              pagination={false}
              size="small"
            />
          </div>
        </Form>
      </Modal>

      {/* 字典项编辑模态框 */}
      <Modal
        title={itemEditMode ? '编辑字典项' : '新增字典项'}
        visible={itemVisible}
        onOk={itemForm.submit}
        onCancel={() => setItemVisible(false)}
      >
        <Form form={itemForm} layout="vertical" onFinish={handleItemSubmit}>
          <Form.Item
            name="label"
            label="项文本"
            rules={[{ required: true, message: '请输入项文本' }]}
          >
            <Input placeholder="请输入项文本" />
          </Form.Item>

          <Form.Item
            name="value"
            label="项值"
            rules={[{ required: true, message: '请输入项值' }]}
          >
            <Input placeholder="请输入项值" />
          </Form.Item>

          <Form.Item name="sort" label="排序">
            <Input type="number" placeholder="请输入排序号" />
          </Form.Item>

          <Form.Item name="status" label="状态" rules={[{ required: true, message: '请选择状态' }]}>
            <Select placeholder="请选择状态">
              <Option value="active">启用</Option>
              <Option value="inactive">禁用</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default DictionaryConfig;